jQuery.validator.methods.compareDate = function (value, element, param) {
    //var startDate = jQuery(param).val() + ":00";补全yyyy-MM-dd HH:mm:ss格式
    //value = value + ":00";
    var startDate = jQuery(param).val();
    var date1 = new Date(Date.parse(startDate.replace("-", "/")));
    var date2 = new Date(Date.parse(value.replace("-", "/")));
    return date1 < date2;
};

var ctx = $("#ctx").val();

function loadError(o) {
    $(o).attr("src", ctx + "/public/images/error.png");
}

// 登录框
function openLoginPage() {
    $('#loginModal').modal("show")
}

/**
 * 忘记密码
 */
function wangjimima() {
    $('#loginModal').modal("hide");
    $('#mimaa').modal("show")
}

// 注册框
function openRegPage() {
    $('#loginModal').modal("hide");
    $("#reg-form").resetForm();
    $("#business-form").resetForm();
    $('#regModal').modal("show");
}

/**
 * 修改商户信息
 */
function openxiugai() {
    getCustomerInfo($("#business-upd-form"));
    $('#xiugaiModal').modal("show")
}

/**
 * 修改个人信息
 */
function openxiugeren() {
    getCustomerInfo($("#customer_upd_form"));
    $('#xiugerenModal').modal("show");
}

/**
 * 修改密码
 */
function openxiumima() {
    $('#xiumima').modal("show");
}

// 退出登录
function logout() {
    sessionStorage.removeItem("session_user");
    $("#logout-container").hide();
    $("#customer-container").show();
    location.reload();
}

function isLogin() {
    var sessionUser = sessionStorage.getItem("session_user");
    return (sessionUser != null && typeof sessionUser != undefined);
}

function getUserInfo() {
    if (isLogin()) {
        var sessionUser = sessionStorage.getItem("session_user");
        return $.parseJSON(sessionUser);
    }
    return null;
}

function createSuit() {
    if (!isLogin()) {
        Alert("您尚未没有登录");
        return;
    }
    if (businessStatus()) {
        location.href = ctx + "/front/user-info-create";
    }
}

/**
 * 浏览器判断只支持IE9及以上浏览器
 * @type {boolean|void}
 */
var browser = (function () {
    var userAgent = window.navigator.userAgent.toLowerCase();
    var isIE = /(msie|trident)/i.test(userAgent);
    var isOpera = userAgent.indexOf("opera") > -1; //判断是否Opera浏览器
    var isEdge = userAgent.indexOf("windows nt 6.1; trident/7.0;") > -1 && !isIE; //判断是否IE的Edge浏览器
    var isFF = userAgent.indexOf("firefox") > -1; //判断是否Firefox浏览器
    var isSafari = userAgent.indexOf("safari") > -1 && userAgent.indexOf("chrome") == -1; //判断是否Safari浏览器
    var isChrome = userAgent.indexOf("chrome") > -1 && userAgent.indexOf("safari") > -1; //判断Chrome浏览器
    var isWechar = userAgent.indexOf("micromessenger") > -1;

    if ((!isIE && !isEdge && !isSafari && !isChrome && !isFF) || isWechar) {
        Alert("为了获得更好的体验,建议使用Chrome,Safari,Firefox或IE内核浏览器");
        return false;
    }
    if (isIE) {
        var version = userAgent.match(/(msie |rv:)(\d+(\.\d+)?)/i)[2];
        if (version < 9) {
            Alert("为了获得更好的体验，网站暂不支持IE8以下浏览器");
            return false;
        }
    }
}());

$(function () {
    $(document).on("keydown", function (e) {
        var btnClose = $("div.layui-layer-dialog .layui-layer-btn .layui-layer-btn0");
        if (e.which === 13 && btnClose.length > 0 && btnClose.text() === "确定") {
            btnClose.click();
            return false;
        }
    });

    setSideNav();

    $("#login-form").validate();
    $("#reg-form").validate({
        rules: {
            password: "required",
            confirmPassword: {
                required: true,
                equalTo: "#password"
            }
        }
    });
    $("#business-form").validate({
        rules: {
            password: "required",
            confirmPassword: {
                required: true,
                equalTo: "#password"
            }
        }
    });
    $("#customer_upd_form,#business-upd-form").validate();
    $("#update_pwd_form").validate({
        rules: {
            updNewPassword: "required",
            updConfirmPassword: {
                equalTo: "#updNewPassword"
            }
        }
    });
    $("#forget_form").validate({
        rules: {
            forgetNewPassword: "required",
            confirmNewPassword: {
                equalTo: "#forgetNewPassword"
            }
        }
    });

    if (isLogin()) {
        $("#logout-container").show();
        $("#customer-container").hide();
        $("#customer_head_img").attr("src", getUserInfo().headImg);
        $("#customer_alias").html(getUserInfo()["alias"]);

        var type = getUserInfo().type;
        if (type == 1) {
            $("#upd_customer_nav").fadeIn();
            $("#upd_business_nav").fadeOut();
        } else {
            $("#upd_customer_nav").fadeOut();
            $("#upd_business_nav").fadeIn();
        }
    } else {
        $("#logout-container").hide();
        $("#customer-container").show();
    }
    
    $("#customer_alias").click(function () {
        userInfoPage();
    });

    /**
     * 登录
     */
    $("#login-btn").click(function () {
        var actionForm = $("#login-form");
        var valid = actionForm.valid();
        if (!valid) {
            return false;
        }
        actionForm.ajaxSubmit({
            type: "post",
            url: ctx + "/front/api/customer/login",
            data: {
                account: $("#loginAccount").val(),
                password: $("#loginPssword").val()
            },
            success: function (rtn) {
                if (rtn.code != 1) {
                    Alert(rtn.message);
                    return;
                }
                sessionStorage.setItem("session_user", rtn.data);
                $('#loginModal').modal("hide");
                $("#logout-container").show();
                $("#customer-container").hide();
                userInfoPage();
            }
        });
    });

    /**
     * 个人用户注册
     */
    $("#reg-btn").click(function () {
        var actionForm = $("#reg-form");
        var valid = actionForm.valid();
        var headImgFile = actionForm.find(":file[name='headImgFile']");
        var headImgFileValue = headImgFile.val();
        if (!valid) {
            return;
        }
        if (headImgFileValue == null || headImgFileValue.length < 1) {
            Alert("请上传头像");
            return false;
        }
        actionForm.ajaxSubmit({
            type: "post",
            url: ctx + "/front/api/customer/regCustomer",
            data: {
                type: 1
            },
            success: function (rtn) {
                if (rtn.code != 1) {
                    Alert(rtn.message);
                    return;
                }
                Alert("注册成功");
                $("#regModal").modal("hide");
                sessionStorage.setItem("session_user", rtn.data);
                $("#logout-container").show();
                $("#customer-container").hide();
                userInfoPage();
            }
        });
    });

    /**
     * 商户注册
     */
    $("#business-reg-btn").click(function () {
        var actionForm = $("#business-form");
        var businessLicenseFile = actionForm.find(":file[name='businessLicenseFile']");
        var businessLicenseFileValue = businessLicenseFile.val();
        var valid = actionForm.valid();
        if (!valid) {
            return;
        }
        if (businessLicenseFileValue == null || businessLicenseFileValue.length < 1) {
            Alert("请上传营业执照");
            return;
        }
        var headImgFile = actionForm.find(":file[name='headImgFile']");
        var headImgFileValue = headImgFile.val();
        if (headImgFileValue == null || headImgFileValue.length < 1) {
            Alert("请上传商标");
            return;
        }
        actionForm.ajaxSubmit({
            type: "post",
            url: ctx + "/front/api/customer/regCustomer",
            data: {
                type: 2
            },
            success: function (rtn) {
                if (rtn.code != 1) {
                    Alert(rtn.message);
                    return;
                }
                Alert("注册成功");
                $("#regModal").modal("hide");
            }
        });
    });

    $("#bqy > li").click(function (o) {
        var $this = $(o.target);
        var type = $this.attr("type");
        $("#type").val(type);
    });

    $(":file").change(function (e) {
        if (window.FileReader) {
            var reader = new FileReader();
        } else {
            Alert("您的设备不支持图片预览功能，如需该功能请升级您的设备！");
        }
        //获取文件
        var fileDom = e.target;
        var file = fileDom.files[0];
        var imageType = /^image\//;
        //是否是图片
        if (!imageType.test(file.type)) {
            Alert("请选择图片！");
            return;
        }
        //读取完成
        reader.onload = function (e) {
            //获取图片dom
            var img = $(fileDom).siblings("img");
            //图片路径设置为读取的图片
            $(img).attr("src", e.target.result);
        };
        reader.readAsDataURL(file);
    });

    /**
     * 密码修改
     */
    $("#update_pwd_btn").click(function () {
        var actionForm = $("#update_pwd_form");
        var valid = actionForm.valid();
        if (!valid) {
            return;
        }
        actionForm.ajaxSubmit({
            type: "post",
            url: ctx + "/front/api/customer/updatePassword",
            data: {
                id: getUserInfo().id
            },
            success: function (rtn) {
                if (rtn.code != 1) {
                    Alert(rtn.message);
                    return;
                }
                Alert("修改成功");
                $("#xiumima").modal("hide");
            }
        });
    });

    /**
     * 忘记密码
     */
    $("#forget_pwd_btn").click(function () {
        var actionForm = $("#forget_form");
        var valid = actionForm.valid();
        if (!valid) {
            return;
        }
        actionForm.ajaxSubmit({
            type: "post",
            url: ctx + "/front/api/customer/updateForgetPassword",
            success: function (rtn) {
                if (rtn.code != 1) {
                    Alert(rtn.message);
                    return;
                }
                Alert("找回密码成功");
                $("#mimaa").modal("hide");
            }
        });
    });

    $("li[name='navmenus'] a").click(function () {
        var $this = $(this);
        var url = $this.attr("url");
        document.location.replace(ctx + url);
    });

    function setSideNav() {
        var location = document.location.href;
        $(".pull-right li a[url]").each(function (i, v) {
            var headUrl = $("header[url]").attr("url");
            var _url = $(v).attr("url");
            if (location.indexOf(_url) > -1 || _url.indexOf(headUrl) > -1) {
                var index = $(".pull-right li a[url]").index($(v));
                var url = ctx + "/public/front/images/home1/border" + (index + 1) + ".png";
                var a = $("<i class='current-menu'></i>").css("background-image", "url(" + url + ")");
                $(v).after(a);
            }
        });
    }

    $(document).on("click", "img[name='nail-img']", function (e) {
        var $this = $(e.target);
        $this.siblings("input").click();
    });

    $('textarea').keyup(function (event) {
        var $this = $(event.target);
        var maxlength = parseInt($this.attr("maxlength"));
        var textareaCount = $this.siblings("div.textareaTip").find("strong");
        var len = $this.val().length;
        textareaCount.html(maxlength - len);
        if (parseInt(textareaCount.text()) < 0) {
            textareaCount.html('0');
            var res = $this.val().substring(0, 140);
            $this.val(res);
        }
    });

    $(".btn-group").hover(function (e) {
        $(this).addClass("open");
    }, function () {
        $(this).removeClass("open");
    });
});

function getCustomerInfo(form) {
    var id = getUserInfo().id;
    $.get(ctx + "/front/api/customer/getCustomerInfo", {id: id}, function (rtn) {
        if (rtn.code != 1) {
            Alert("获取数据失败");
            return;
        }

        var data = rtn.data;
        var properties = Object.getOwnPropertyNames(data);
        for (var i = 0; i < properties.length; i++) {
            form.find("*[name='" + properties[i] + "']").not(":file").val(data[properties[i]]);
            form.find("*[name='" + properties[i] + "']").not(":file").text(data[properties[i]]);
            $("img[name='headImgUrl']").attr("src", data["headImg"]);
            $("img[name='businessLicenseImgUrl']").attr("src", data["businessLicense"]);
        }
        $(":radio[name='upd_sex'][value='"+data.sex+"']").prop("checked", "checked");

        // 设置自我介绍的字数限制
        form.find("textarea").each(function (i, v) {
            var $this = $(v);
            var maxlength = parseInt($this.attr("maxlength"));
            var textareaCount = $this.siblings("div.textareaTip").find("strong");
            var len = $this.val().length;
            textareaCount.html(maxlength - len);
            if (parseInt(textareaCount.text()) < 0) {
                textareaCount.html('0');
                var res = $this.val().substring(0, 140);
                $this.val(res);
            }
        });
    });
}

/**
 * 提交修改
 * @param actionForm
 */
function updateCustomer(actionForm) {
    var valid = actionForm.valid();
    if (!valid) {
        return;
    }

    actionForm.ajaxSubmit({
        type: "post",
        url: ctx + "/front/api/customer/updateCustomer",
        data: {
            sex: $(":radio[name='upd_sex']:checked").val()
        },
        success: function (rtn) {
            if (rtn.code != 1) {
                Alert(rtn.message);
                return;
            }
            Alert("修改成功", function () {
                sessionStorage.removeItem("session_user");
                sessionStorage.setItem("session_user", rtn.data);
                document.location.reload();
            });
        }
    });
}

function userInfoPage() {
    document.location.replace(ctx + "/front/user_info/" + getUserInfo().id+"/0");
}

function businessStatus() {
    var userInfo = getUserInfo();
    if (userInfo.type === 2) {
        if (userInfo.auditStatus === 1) {
            Alert("商户正在审核中");
            return false;
        } else if (userInfo.auditStatus === 3) {
            Alert("商户审核不通过");
            return false;
        }
    }
    return true;
}


/**
 * 注册发送短信验证
 * @param type
 */
function sendSms(type, regType) {
    var account;
    var btn;
    // 注册
    if (type == 1) {
        account = regType = 1 ? $("#account") : $("#business-account");
        btn = regType = 1 ? $("#sms-btn-personal") : $("#sms-btn-business");
    }
    // 找回密码
    else if (type == 2) {
        account = $("#forget_account");
        btn = $("#sms-btn-forget");
    }
    if ($.trim(account.val()) == "") {
        Alert("请输入手机号", function () {
            account.focus();
        });
        return false;
    }
    $.post(ctx + "/front/api/customer/sendSms", {account: account.val(), type: type}, function (rtn) {
        new invokeSettime(btn);
        if (rtn.code != 1) {
            Alert(rtn.message);
            return;
        }
    });
}

function invokeSettime(obj){
    var countdown=120;
    settime(obj);
    function settime(obj) {
        if (countdown == 0) {
            $(obj).attr("disabled",false);
            $(obj).text("获取验证码");
            countdown = 60;
            return;
        } else {
            $(obj).attr("disabled",true);
            $(obj).text("(" + countdown + ") s 重新发送");
            countdown--;
        }
        setTimeout(function() {
                settime(obj) }
            ,1000)
    }
}

// 弹出框
function Alert(msg, callback) {
    if (typeof callback === "function") {
        layer.open({
            content: msg,
            yes: function (index) {
                callback.call(this);
                layer.close(index);
            }
        });
        return;
    }
    layer.alert(msg);
}

/**
 * 确认框
 * @param msg 消息
 * @param callback 回调
 * @constructor
 */
function Confirm(msg, callback) {
    layer.open({
        content: msg,
        btn: ["确定", "取消"],
        btn1: function (index) {
            callback.call(this);
            layer.close(index);
        }
    });
}